import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {ElMessage} from "element-plus";

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect: '/user',
    children: [
      {path: '/user', component: () => import('../views/user/UserView.vue')},
      {path: '/vehicle', component: () => import('../views/vehicle/VehicleView.vue')},
      {path: '/geofence', component: () => import('../views/geofence/GeofenceView.vue')},
      {path: '/geofenceMap', component: () => import('../views/geofence/GeofenceMapView.vue')},
      {path: '/application', component: () => import('../views/schedule/ApplicationView.vue')},
      {path: '/audit', component: () => import('../views/schedule/AuditView.vue')},
      {path: '/distribute', component: () => import('../views/schedule/DistributeView.vue')},
      {path: '/dict', component: () => import('../views/dictionary/DictView.vue')},
      {path: '/dictOption', component: () => import('../views/dictionary/DictOptionView.vue')}
    ]
  },
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // },
  {
    path: '/login',
    component: () => import( '../views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
//在路由切换前需要判断用户是否已经登录
/**
 * to: 将要进入的目标路由对象
 * from：当前路由对象
 * next:前进到下一个路由的函数
 */
router.beforeEach((to,from,next)=>{
  //从本地存储的对象中获取用户信息
  let user = localStorage.user;
  //判断用户未登录且尝试访问要登录的页面不是登录页，则需要重定向到登录页，并提示需要先登录
  if(to.path!=="/login" && !user && to.path !== "/"){
    next({path:'/login',query:{redirect: to.fullPath}},ElMessage.error("请先登录"))
  }else {
    //允许路由切换
    next();
  }
})
export default router
